import React from "react";
import {Button} from "antd";
import {IconFont} from "@/components/Icon";
import {useGlobalStore} from "@/store/global";

type PropsType = {
    iconSize?: number
}

const SwitchDark: React.FC<PropsType> = ({iconSize = 22}) => {
    const {isDark, setGlobalState} = useGlobalStore();
    const themeChange = (event: { clientX: number; clientY: number; }) => {
        const isAppearanceTransition = document.startViewTransition() && !window.matchMedia('(prefers-reduced-motion: reduce)').matches
        if (!isAppearanceTransition || !event) return setGlobalState({key: "isDark", value: !isDark})
        const x = event.clientX
        const y = event.clientY
        const endRadius = Math.hypot(
            Math.max(x, innerWidth - x),
            Math.max(y, innerHeight - y)
        )
        const transition = document.startViewTransition(() => {
        })
        transition.ready.then(() => {
            const clipPath = [
                `circle(0px at ${x}px ${y}px)`,
                `circle(${endRadius}px at ${x}px ${y}px)`,
            ]
            document.documentElement.animate(
                {
                    clipPath: !isDark ? [...clipPath].reverse() : clipPath,
                },
                {
                    duration: 400,
                    easing: 'ease-in',
                    pseudoElement: !isDark
                        ? '::view-transition-old(root)'
                        : '::view-transition-new(root)',
                }
            )
            setGlobalState({key: "isDark", value: !isDark})
        })
    }
    return (
        <Button
            type="text"
            size="large"
            className="absolute top-[13px] right-[15px]"
            icon={<IconFont style={{fontSize: iconSize}} type={isDark ? "icon-sun" : "icon-moon"}/>}
            onClick={themeChange}
        ></Button>
    );
};

export default SwitchDark;
